package com.wfh.mianshiji.ws.handler;

import cn.hutool.json.JSONUtil;
import com.wfh.mianshiji.common.ErrorCode;
import com.wfh.mianshiji.exception.BusinessException;
import com.wfh.mianshiji.ws.model.Message;
import com.wfh.mianshiji.ws.model.enums.MessageTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Title: MessageRouter
 * @Author wangfenghuan
 * @Package com.wfh.mianshiji.ws.handler
 * @Date 2025/10/31 16:15
 * @description: 消息路由（Spring WebSocket 版）
 */
@Slf4j
@Component
public class MessageRouter {

    private final Map<String, BaseHandler> handlerMap;

    public MessageRouter(List<BaseHandler> handlers) {
        this.handlerMap = new ConcurrentHashMap<>();
        for (BaseHandler handler : handlers) {
            handlerMap.put(handler.getMessageType().getValue(), handler);
        }
    }

    public void route(String message, WebSocketSession session) {
        try {
            if (!session.isOpen()) {
                return;
            }

            Message msg = JSONUtil.toBean(message, Message.class);
            if (msg.getType() == null) {
                log.warn("消息类型为空，内容: {}", message);
                sendError(session, "消息类型不能为空");
                return;
            }

            BaseHandler handler = handlerMap.get(msg.getType());
            if (handler == null) {
                log.warn("不支持的消息类型: {}", msg.getType());
                sendError(session, "不支持的消息类型: " + msg.getType());
                return;
            }

            handler.handle(msg, session);

        } catch (Exception e) {
            log.error("处理消息时发生异常，消息内容: {}", message, e);
            // 不抛出异常，避免中断整个 WebSocket 连接
            sendError(session, "消息处理失败: " + e.getMessage());
        }
    }

    private void sendError(WebSocketSession session, String errorMsg) {
        if (!session.isOpen()) {
            return;
        }
        try {
            Message err = new Message();
            err.setType("error");
            session.sendMessage(new TextMessage(JSONUtil.toJsonStr(err)));
        } catch (IOException e) {
            log.error("发送错误消息失败", e);
        }
    }
}